package com.ocean.security.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.ocean.security.model.UserLoginDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;

/**
 * 自定义登录认证
 *
 * @author zhang
 * @since 2021/9/10
 */
@Slf4j
public class CustomUsernamePasswordAuthenticationFilter extends UsernamePasswordAuthenticationFilter {

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
        if (request.getContentType() != null) {
            //JSON请求
            if (request.getContentType().equals(MediaType.APPLICATION_JSON_UTF8_VALUE)
                    || request.getContentType().equals(MediaType.APPLICATION_JSON_VALUE)) {
                ObjectMapper mapper = new ObjectMapper();
                UsernamePasswordAuthenticationToken authRequest = null;
                try (InputStream is = request.getInputStream()) {
                    UserLoginDTO authenticationBean = mapper.readValue(is, UserLoginDTO.class);
                    authRequest = new UsernamePasswordAuthenticationToken(
                            authenticationBean.getUsername(), authenticationBean.getPassword());
                } catch (IOException e) {
                    log.error("JSON登录错误", e);
                    authRequest = new UsernamePasswordAuthenticationToken(
                            "", "");
                }
                super.setDetails(request, authRequest);
                return super.getAuthenticationManager().authenticate(authRequest);
            }
        }
        //表单
        return super.attemptAuthentication(request, response);
    }
}
